package com.winit.deploy.task.phpTask;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.util.JSONFileUtil;
import com.winit.core.task.Task;
import com.winit.deploy.bean.DeployEnum;
import com.winit.deploy.bean.WinitPhpInfo;
import com.winit.deploy.server.WinitPhpServer;
import com.winit.deploy.util.DeployUtil;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * php工程安装
 * Created by wangjian on 16/10/17.
 */
public class PhpInstallTask extends Task {

    private static Logger logger = LoggerFactory.getLogger(PhpInstallTask.class);

    private WinitPhpServer phpServer;


    public PhpInstallTask(String taskId, Integer expireTime,WinitPhpServer phpServer) {
        super(taskId, expireTime);
        this.phpServer = phpServer;
    }

    @Override
    public TaskStatus call() throws Exception {
        logger.info("com.winit.deploy.task.phpTask.PhpInstallTask.call start taskId="+this.taskId);
        WinitPhpInfo info = this.phpServer.getPhpInfo();
        String projectName = info.getProjectName();
        String editionNum = info.getEditionNum();

        String linuxUser = "apache";
        JSONArray array = JSONFileUtil.getFileJsonForBean(Thread.currentThread().getContextClassLoader().getResource("").getPath()
                + "data/ui_list.json", JSONArray.class);
        if(array.contains(ProjectUtil.getTrunkProjectName(projectName))){
            linuxUser = info.getDstUser();
        }
        boolean flag = this.phpServer.doInstall(linuxUser);
        if(flag){
            if(this.taskId.startsWith("staging")){
                DeployUtil.updateProjectVersion(projectName,editionNum, DeployEnum.STAGING);
            }
            if(this.taskId.startsWith("online")){
                DeployUtil.updateProjectVersion(projectName,editionNum,DeployEnum.ONLINE);
                DeployUtil.cpOnlineVersionToNas(projectName,editionNum);
            }
        }
        logger.info("com.winit.deploy.task.phpTask.PhpInstallTask.call end taskId="+this.taskId);
        return flag?TaskStatus.STATUS_SUCCESS:TaskStatus.STATUS_ERROR;
    }
}
